import {
  Component, Input,
  OnInit,
} from '@angular/core';
import { UploadFile, UploadXHRArgs } from '@shared/apes/upload';
import { toBoolean, toNumber } from '@shared/apes/core/util/convert';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { dateFormat } from '../../../utils/utils';
import { saveAs } from 'file-saver';

@Component({
  selector: 'apes-upload-dialog',
  templateUrl: './apes-uploadDialog.component.html',
})
export class ApesUploadDialogComponent implements OnInit {

  uploading = false;
  _fileList: UploadFile[] = [];
  previewImage = '';
  previewVisible = false;
  showList: any;
  imgType: any = 'image/png,image/jpeg,image/gif,image/bmp';
  title: any;

  @Input() disabled = false;
  @Input() type: any; //="image/png,image/jpeg,image/gif,image/bmp";
  @Input() limit: any;
  @Input() showDownload: any = true;
  @Input() showRemove: any = true;
  @Input() showFile: any = false;
  @Input() multiple: boolean = false;
  @Input() accept: any;

  onChange: (value: any) => void = () => null;
  onTouched: () => void = () => null;

  constructor(
    private  apiService: ApiService,
    private msg: ApesMessageService,
  ) {
  }

  ngOnInit() {
    // console.log(this._fileList);
  }

  get fileList(): UploadFile[] {
    return this._fileList || [];
  }

  set fileList(input: UploadFile[]) {
    let value = input;
    if (this._fileList === value) {
      return;
    }
    this._fileList = value;
  }

  /** 显示数量 **/
  showLimit() {
    // let _limit
    return this.limit ? '允许上传最多' + this.limit + '个文件' : '不限个数';
  }

  /** 控制上传类型、数量和是否重复**/
  beforeUpload = (file: UploadFile): boolean => {
    let _type = this.type ? this.type : file.type;
    let _limit = toNumber(this.limit, null);
    let tempFileList = this.fileList;
    let isRepeat = false;
    if (_type.indexOf(file.type) == -1 || (file.type == '' && _type != file.type)) {
      let check = true;
      if (this.accept) {
        let accept = file.name.split('.');
        if (this.accept.indexOf(accept[accept.length - 1]) != -1) {
          check = false;
        }
      }
      if (check) {
        this.msg.error('请上传指定类型文件');
        return false;
      }
    }
    if (_limit !== null) {
      if (this.fileList.length < _limit) {
        if (this.fileList.length == 0) {
          // this.fileList.push(file);
        } else {
          tempFileList.map((files) => {
            if (files.name == file.name) {
              isRepeat = true;
            }
          });
          if (isRepeat) {
            this.msg.error('请勿重复上传相同文件');
            return false;
          } else {
            // this.fileList.push(file);
          }
        }
      } else {
        this.msg.error('超出上传限制数量');
        return false;
      }
    } else {
      tempFileList.map((files) => {
        if (files.name == file.name) {
          isRepeat = true;
        }
      });
      if (isRepeat) {
        this.msg.error('请勿重复上传相同文件');
        return false;
      } else {
        // this.fileList.push(file);
      }
    }
    // this.handleUpload();
    return true;
  };

  /** 上传操作 **/
  handleUpload(): void {
    // 判断
    this.uploading = true;
    this.apiService.upload(this.fileList).subscribe(
      (event: any) => {
        const returnFile = event.body;
        // this.formControl.patchValue(returnFile);
        // this.model[this.key] = returnFile;
        this.showFilesList(returnFile);
        this.msg.success('上传成功');
        this.uploading = false;
      },
      err => {
        console.log(err);
        this.uploading = false;
        this.msg.error('上传失败,请核实文件是否能正常上传！');
      },
    );
  }

  customReq = (item: UploadXHRArgs) => {
    this.uploading = true;
    const formData = new FormData();
    formData.append('file', item.file as any);
    formData.append('id', '1000');
    return this.apiService.upload([item.file]).subscribe(
      (event: any) => {
        const returnFile = event.body[0];
        this.showFilesList(returnFile);
        this.msg.success('上传成功');
        this.uploading = false;
        item.onSuccess!(event.body, item.file!, event);
      },
      err => {
        console.log(err);
        this.uploading = false;
        this.msg.error('上传失败,请核实文件是否能正常上传！');
        // item.onError!('test', item.file!);
        this.removeFilesList(item.file);
      },
    );
  };


  /** 处理上传文件 **/
  showFilesList(returnFile) {
    let bAdd = true;
    for (let item of this.fileList) {
      if (item.name == returnFile.fileName || item.id == returnFile.id) {
        item.thumbUrl = 'fileserver/view/' + returnFile.id;
        item.id = returnFile.id;
        item.status = 'done';
        item.iconType = 'thumbnail';
        item.isUploading = false;
        this.fileList = [...this.fileList];
        bAdd = false;
      }
    }
    if (bAdd) {
      returnFile.thumbUrl = 'fileserver/view/' + returnFile.id;
      returnFile.status = 'done';
      returnFile.iconType = 'thumbnail';
      returnFile.isUploading = false;
      this.fileList = [...this.fileList, returnFile];
    }

    this.onChange(JSON.stringify(this.fileList));
  }

  removeFilesList(file: UploadFile) {
    this.fileList = this.fileList.filter(x => x.name !== file.name);
    this.onChange(this.fileList);
  }


  // showFilesList(returnFile) {
  //   let tempFileList = this.fileList.filter(x => x.lastModified == undefined);
  //   returnFile.map((file) => {
  //     if (!file.url && file.id && this.imgType.indexOf(file.type) > -1) {
  //       file.url = 'fileserver/view/' + file.id;
  //     }
  //     tempFileList.push(file);
  //   });
  //   let duplicateFile = [];
  //   tempFileList.forEach((temp) => {
  //     let check = true;
  //     if (duplicateFile.length == 0) {
  //       duplicateFile.push(temp);
  //     } else {
  //       duplicateFile.forEach((file) => {
  //         if (file.id == temp.id || file.name == temp.name) {
  //           check = false;
  //         }
  //       });
  //       if (check) {
  //         duplicateFile.push(temp);
  //       }
  //     }
  //   });
  //
  //   this.fileList = duplicateFile;
  //   this.onChange(this.fileList);
  // }

  /** 删除文件 **/
  handleRemove = (file: UploadFile) => {
    if (this.showFile) {
      return false;
    } else {
      this.fileList = this.fileList.filter(x => x.name !== file.name);
      this.onChange(this.fileList);
      return true;
    }
  };

  /** 是否允许下载 **/
  handleShowList = () => {
    let showDownload = this.showDownload;
    let showRemove = this.showRemove;
    // let showPreviewIcon = this.imgType.indexOf(this.type) > -1;
    this.showList = {
      showPreviewIcon: true,
      showRemoveIcon: toBoolean(showRemove),
      showDownloadIcon: toBoolean(showDownload),
    };
    return this.showList;
  };

  /** 下载文件 **/
  handleDownload() {
    this.apiService.download(this.fileList).subscribe(
      (event: any) => {
        let fileName = dateFormat('yyyyMMddHHmmss', new Date());
        let body = event.body;
        if (body.type === 'application/octet-stream') {
          saveAs(body, decodeURI(`${fileName}.zip`));
        }
      },
    );
  };

  /** 判断是否显示预览图 **/
  handlePreview = (file: UploadFile) => {
    if (file.type.indexOf('image') > -1) {
      if (file.url) {
        this.previewImage = file.url;
      } else {
        this.previewImage = 'fileserver/view/' + file.id || file.thumbUrl;
      }
      this.previewVisible = true;
    }
  };

  writeValue(value: any): void {
    this.fileList = JSON.parse(value) || [];
  }

  registerOnChange(fn: (_: any) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

}

